/******************************************************************************* 
 * Copyright (C) 2012-2015 Microfountain Technology, Inc. All Rights Reserved. 
 * 
 * Unauthorized copying of this file, via any medium is strictly prohibited.   
 * Proprietary and confidential
 * 
 * Last Modified: 2015-10-21 14:58:11
 ******************************************************************************/
package cn.com.xy.sms.sdk.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import cn.com.xy.sms.sdk.Iservice.OnlineUpdateCycleConfigInterface;
import cn.com.xy.sms.sdk.action.AbsSdkDoAction;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.AirManager;
import cn.com.xy.sms.sdk.db.DBManager;
import cn.com.xy.sms.sdk.db.MenuInfoManager;
import cn.com.xy.sms.sdk.db.ParseItemManager;
import cn.com.xy.sms.sdk.db.TrainManager;
import cn.com.xy.sms.sdk.db.bizport.BizportDBManager;
import cn.com.xy.sms.sdk.db.entity.DomainDBManager;
import cn.com.xy.sms.sdk.db.entity.JarSubInfo;
import cn.com.xy.sms.sdk.db.entity.JarSubInfoManager;
import cn.com.xy.sms.sdk.db.entity.SceneRuleManager;
import cn.com.xy.sms.sdk.db.entity.SysParamEntityManager;
import cn.com.xy.sms.sdk.dex.DexUtil;
import cn.com.xy.sms.sdk.iccid.IccidLocationUtil;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.net.util.SigntureUtil;
import cn.com.xy.sms.sdk.service.pubInfo.PubInfoNetService;
import cn.com.xy.sms.sdk.tagsearch.TagManager;
import cn.com.xy.sms.util.SdkCallBack;
import cn.com.xy.sms.util.SdkParamUtil;
/*SDK-616 hewengao 20160912 start*/
import cn.com.xy.sms.sdk.threadpool.SmartSmsThreadPoolManager;
import android.os.Process;
/*SDK-616 hewengao 20160912 end*/
public class InitUtil {

    /*SMARTISAN-129 songzhirong 20160819 start*/ 
    private static boolean isReIniting = false;
    private final static Object reInitLock = new Object();
    /*SMARTISAN-129 songzhirong 20160819 end*/
    private static boolean isIniting = false;
    private final static Object lock = new Object();
    /*SDK-673 hewengao 20161114 start*/
    public static boolean isLoadedBigJar =false;
    /*SDK-673 hewengao 20161114 end*/
    public static void checkInit() {
        try {
            // 检测是否首次执行
            synchronized (lock) {
                if (isIniting)
                    return;
                isIniting = true;
            }
            /*SDK-654 hewengao 20161026 start*/
            /*SDK-673 hewengao 20161114 start*/
            //if(isInitFinish == false) {
                // 初始化数据
//                initInerData();
//                /*SDK-457 hewengao 20160525 start */
//                DexUtil.beforeInitBigJar();
//                /*SDK-457 hewengao 20160525 end */
            //}
            /*SDK-673 hewengao 20161114 start*/
             /*SDK-654 hewengao 20161026 end*/
            // 检测更新算法包
            JarSubCheckQueue.runJarSubCheckQueue();
            // 检测是否需要情景、情景规则升级
            SceneconfigUtil.updateData();

            InitUtil.postConutData();//统计数据上传
            
            // 公众号明文签名上传
            PubInfoNetService.uploadPubInfoSign();

        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "checkInit: ", e);

        } finally {
            isIniting = false;
        }
    }
    public static void postConutData() {
     try {
             String flag = SysParamEntityManager.getStringParam(Constant.getContext(), Constant.SCENE_CENSUS_ONLINE);
                /*SDK-392  hewengao 20160416 start*/
             boolean sceneMenuReportOn =DexUtil.geOnOffByType(OnlineUpdateCycleConfigInterface.ON_OFF_MENU_SCENE_REPORT);
             boolean sceneReportOn =DexUtil.geOnOffByType(OnlineUpdateCycleConfigInterface.ON_OFF_SCENE_REPORT);
             if ("1".equals(flag) || sceneMenuReportOn) {
                 // 打点数据上传
                 SceneCountActionUtil.postSceneCountAction();
                    //菜单打点统计数据上传
                 MenuActionCountActionUtil.postMenuCountAction();
             } else if ("2".equals(flag) || sceneReportOn) {
                 // 检测是否上报情景号
                 SceneconfigUtil.postqueryIccidScene();
             }
             /*SDK-392  hewengao 20160416 end*/
         } catch (Throwable e) {
            LogManager.e(Constant.TAG, "checkInit: ", e);
         }
    }
    
    public static void initTrainOrAirDb(String dbFilePath, int type) {
        String filePath = Constant.getDRAWBLE_PATH() + dbFilePath;
        // 0代表火车数据，1代表飞机数据
        if (FileUtils.isFileExists(filePath)) {
            if (type == 0) {
                // TrainManager.checkUpdateData();
                TrainManager.importTrainData(Constant.getContext());
            } else if (type == 1) {
                // AirManager.checkUpdateData();
                AirManager.importAirData(Constant.getContext());
            }
        }
    }

    private static boolean isInerDataIniting = false;

    /**
     * 描述： 插入数据
     * 
     * @return void
     */
    public static void initInerData() {
        synchronized (lock) {
            if (isInerDataIniting){
                /* SDK-567 huangzhiqiang 20160728 start */
                DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "initInerData running or complete", null);
                /* SDK-567 huangzhiqiang 20160728 end */
                return;
            }
            isInerDataIniting = true;
        }
        try {
            /* SDK-567 huangzhiqiang 20160728 start */
            DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "initInerData start", null);
            /* SDK-567 huangzhiqiang 20160728 end */
            SysParamEntityManager.setParam("init_xiaoyuan_sdk", "0");

//            long startAll = System.currentTimeMillis();

            /* SDK-419 huangzhiqiang 20160504 start */
            ExecutorService sdkInitPool = Executors.newSingleThreadExecutor();

            sdkInitPool.execute(new Runnable() {

                @Override
                public void run() {
                    /*SDK-616 hewengao 20160912 start*/
                    SmartSmsThreadPoolManager.setThreadNameAndPriority("xy-sdkinitpool-1", 
                            Process.THREAD_PRIORITY_BACKGROUND);
                    /*SDK-616 hewengao 20160912 end*/
                    // long start = System.currentTimeMillis();
                    // 批量导入菜单相关内嵌sql
                    initMenuData();
                    // long end = System.currentTimeMillis();
                    // LogManager.d("xiaoyuan_test", "initInerData initMenuData time: "+(end-start)+" "+(end-start)/1000+"秒");

                    // start = System.currentTimeMillis();
                    // 初始化公众号logo资源
                    initPublicLogo();
                    // end = System.currentTimeMillis();
                    // LogManager.d("xiaoyuan_test", "initInerData initPublicLogo time: "+(end-start)+" "+(end-start)/1000+"秒");

                    // start = System.currentTimeMillis();
                    // 初始化图片资源
                    initDrawble();
                    // end = System.currentTimeMillis();
                    // LogManager.d("xiaoyuan_test", "initInerData initDrawble time: "+(end-start)+" "+(end-start)/1000+"秒");

                    // start = System.currentTimeMillis();
                    // 初始化火车和飞机的地点参数
                    initTrainOrAirDb("train_data.txt", 0);
                    // end = System.currentTimeMillis();
                    // LogManager.d("xiaoyuan_test", "initInerData initTrainOrAirDb time: "+(end-start)+" "+(end-start)/1000+"秒");

                    // start = System.currentTimeMillis();
                    initTrainOrAirDb("air_data.txt", 1);
                    // end = System.currentTimeMillis();
                    // LogManager.d("xiaoyuan_test", "initInerData initTrainOrAirDb time: "+(end-start)+" "+(end-start)/1000+"秒");

                    initDomainList();

                    initTag();
                }
            });
            sdkInitPool.shutdown(); // 线程任务执行完后关闭线程池

            // long start = System.currentTimeMillis();
            // 初始化算法
            initAlgorithm();
            // long end = System.currentTimeMillis();
            // LogManager.d("xiaoyuan_test", "initInerData initAlgorithm time: "+(end-start)+" "+(end-start)/1000+"秒");

            while (!sdkInitPool.awaitTermination(10, java.util.concurrent.TimeUnit.MILLISECONDS)) {
                // 等待线程执行完成
            }
            /* SDK-419 huangzhiqiang 20160504 end */
//            long endAll = System.currentTimeMillis();
//            LogManager.e("xiaoyuan_init", "new initInerData 总耗时 time: " + (endAll - startAll), null);

            // SysParamEntityManager.setParam("init_xiaoyuan_sdk", "1");
            /* SDK-567 huangzhiqiang 20160728 start */
            DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "initInerData complete", null);
            /* SDK-567 huangzhiqiang 20160728 end */
        } catch (Throwable e) {

            LogManager.e(Constant.TAG, "initInerData: error: ", e);
        } finally {
            SysParamEntityManager.setParam("init_xiaoyuan_sdk", "1");
            /* SDK-567 huangzhiqiang 20160728 start */
            DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "initInerData end", null);
            /* SDK-567 huangzhiqiang 20160728 end */
            // 初始化完毕，回调事件
            DuoquUtils.getSdkDoAction().onEventCallback(AbsSdkDoAction.SDK_EVENT_INIT_COMPLETE, null);
        }
    }

    /**
     * 批量导入内嵌sql
     * 
     * @throws Throwable
     * @throws IOException
     */
    public static void initNeiQianSql() throws IOException, Exception {
        /*SDK-464 hewengao 20160530 start*/
        XyUtil.unZip(
                FileUtils.getAssetManager()
                        .open("duoqu_nqsql.zip"), "duoqu_nqsql.zip",
                Constant.getINITSQL_PATH());
        /*SDK-464 hewengao 20160530 end*/
        MenuInfoManager.insertMenuData();
    }


    public static void initTag(){
        /*SDK-778 kangwenbo 20170504 start*/
        if("XHFBWgoQHUAWEI3".equals(KeyManager.channel)){
            TagManager.updateTag();
        }
        /*SDK-778 kangwenbo 20170504 end*/
    }

    public static void initDomainList(){
        if("XHFBWgoQHUAWEI3".equals(KeyManager.channel)){
            DomainDBManager.getInstance().initDataToDb();
        }
    }

    /*
     * public static void updateJarPackage() { int type =
     * SysParamEntityManager.getIntParam(Constant.getContext(),
     * Constant.ONLINE_UPDATE_SDK); LogManager.i("updateJarNow", "type=" +
     * type); if (type != 0) { int day =
     * SysParamEntityManager.getIntParam(Constant.getContext(),
     * Constant.ONLINE_UPDATE_SDK_PERIOD); LogManager.i("updateJarNow", "day=" +
     * day); if (day <= 0) { day = 1; } // JarSubInfo jarSubInfo =
     * JarSubInfoManager.queryJarSubInfo("parseUtilMain"); //
     * PrintTestLogUtil.printTestLog("JarSubInfo", "parseUtilMain jarSubInfo=" +
     * jarSubInfo); // // if (jarSubInfo == null) { //
     * JarSubInfoManager.insertOrUpdateJarSubInfo("parseUtilMain", "-1",
     * JarSubInfoManager.USED); // } // jarSubInfo =
     * JarSubInfoManager.queryJarSubInfo("ParseHelper"); // if (jarSubInfo ==
     * null) { // JarSubInfoManager.insertOrUpdateJarSubInfo("ParseHelper",
     * "-1", JarSubInfoManager.USED); // }
     * 
     * // 调用解析，最后启动检测任务 JarSubCheckQueue.runJarSubCheckQueue(); } }
     */

    /**
     * 旧版本初始化算法
     */
    public static void oldInitAlgorithm() {
        try {
            /* SDK-567 huangzhiqiang 20160728 start */
            DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "oldInitAlgorithm start", null);
            /* SDK-567 huangzhiqiang 20160728 end */
            JarSubInfo jarSubInfo = JarSubInfoManager
                    .queryJarSubInfo("parseUtilMain");// 查询是tb_jar_list
            // 本地资源版本
            String localVersion = null;
            if (jarSubInfo != null && !StringUtils.isNull(jarSubInfo.version)) {
                localVersion = jarSubInfo.version;
            }

            // Assets资源版本
            String assetVersion = FileUtils
                    .getAssetsTxtFileContent(Constant.ALGORITHM_VERSION_FILE);

            if (!StringUtils.isNull(localVersion)
                    && !compareVersion(localVersion, assetVersion)) {
                return;
            }
            try {
                SysParamEntityManager.clearOldData(false);
                SysParamEntityManager.setParam("sms_sdk_init", "0");
                /*SDK-464 hewengao 20160530 start*/
                XyUtil.unZip(FileUtils.getAssetManager()
                        .open("duoqu_parse.zip"), "parse.zip",
                        Constant.getPARSE_PATH(), true, assetVersion, true);
                /*SDK-464 hewengao 20160530 end*/
                ParseItemManager.updateParse(Constant.getContext());// 写入数据库
                JarSubCheckQueue.updateParseVersion();
                /*SDK-673 hewengao 20161114 start*/
//                chJarmod();
                /*SDK-673 hewengao 20161114 end*/
                SysParamEntityManager.setParam("sms_sdk_init", "1");
                /* SDK-567 huangzhiqiang 20160728 start */
                DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "oldInitAlgorithm complete", null);
                /* SDK-567 huangzhiqiang 20160728 end */
            } catch (Throwable e) {
//                e.printStackTrace();
                LogManager.e(Constant.TAG, "oldInitAlgorithm: ", e);
            }
        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "oldInitAlgorithm: ", e);
        } finally {
            /* SDK-567 huangzhiqiang 20160728 start */
            DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "oldInitAlgorithm end", null);
            /* SDK-567 huangzhiqiang 20160728 end */
        }
    }

    /**
     * 初始化算法
     */
    public static void initAlgorithm() {
        if (DuoquUtils.getAidlAction().supportAidlAction()) {
            SysParamEntityManager.setParam("sms_sdk_init", "1");
            return;
        }
        try {
            /* SDK-567 huangzhiqiang 20160728 start */
            DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "initAlgorithm run", null);
            /* SDK-567 huangzhiqiang 20160728 end */
            updateSmartAlgorithmPver();
            // 如果不存在duoqu_parse_version.txt或duoqu_parse_version.txt的内容只有一个数字时走旧的初始化算法流程
            if (runOldInitAlgorithm()) {
                oldInitAlgorithm();
                return;
            }

            // 所有需要更新的算法包名称对应版本号信息HashMap
            HashMap<String, String> needUpdateParseInfoMap = getNeedUpdateParseInfoMap();
            if (needUpdateParseInfoMap == null) {
//                LogManager.e("initduoqu_parse", "assets下缺少"
//                        + Constant.ALGORITHM_VERSION_FILE + "文件，无法进行算法更新",null);
                /* SDK-567 huangzhiqiang 20160728 start */
                DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "initAlgorithm data is null", null);
                /* SDK-567 huangzhiqiang 20160728 end */
                return;
            }

            if (needUpdateParseInfoMap.isEmpty()) {
                LogManager.i("initduoqu_parse", "没有需要更新的算法包");
                /* SDK-567 huangzhiqiang 20160728 start */
                DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "initAlgorithm complete", null);
                /* SDK-567 huangzhiqiang 20160728 end */
                return;
            }

            /* SDK-567 huangzhiqiang 20160728 start */
            DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "initAlgorithm start", null);
            /* SDK-567 huangzhiqiang 20160728 end */

            LogManager.i("initduoqu_parse", "开始初始化算法配置");
            SysParamEntityManager.setParam("sms_sdk_init", "0");
            String tempParseFolderPath = Constant.getTempPARSE_PATH();
            String parseFolderPath = Constant.getPARSE_PATH();
            // 解压assets下duoqu_parse.zip到临时文件夹parse_temp
            
            /*SDK-464 hewengao 20160530 start*/
            XyUtil.unZip(
                   FileUtils.getAssetManager().open("duoqu_parse.zip"), "parse.zip",
                    tempParseFolderPath, false, null, false);
            /*SDK-464 hewengao 20160530 end*/

            Set<Entry<String, String>> sets = needUpdateParseInfoMap.entrySet();
            List<String> parseNameList = getParseNameList(parseFolderPath);// 获取parse文件夹下去除后缀及版本号后的算法包名称,用于判断是否需要删除旧的jar与dex文件
            List<String> jarSqlList = new ArrayList<String>(); // 存放批量插入tb_jar_lis数据时需要使用的SELECT
                                                               // UNION ALL语句集合
            StringBuilder sbrJarListSelectSql = new StringBuilder(); // 存放批量插入tb_jar_lis数据时需要使用的SELECT
                                                                     // UNION
                                                                     // ALL语句
            int maxSqlLine = 300; // SELECT UNION ALL语句条数最大上限
            int sqlLineCount = 0; // SELECT UNION ALL语句条数计数器
            String parseFileName = null;
            String parseName = null;
            String parseVersion = null;

            try {
                // parseNameList为null代表为第一次初始化，不需要设置脚本状态
                if (parseNameList != null) {
                    try {
                        // 将原有的脚本状态设置为初始化临时标记，用于之后删除重复数据
                        ParseItemManager.updateStatue(ParseItemManager.NORMAL, ParseItemManager.INITTAG);
                    } catch (Throwable e) {
                        LogManager.e(Constant.TAG, e.getMessage(), e);
                    }
                }

                for (Entry<String, String> entry : sets) {
                    parseFileName = entry.getKey();
                    parseVersion = entry.getValue();

                    if (StringUtils.isNull(parseFileName)
                            || StringUtils.isNull(parseVersion)) {
                        continue;
                    }
                    parseName = parseFileName.replace(".jar", "").trim();

                    // 更新算法包jar文件
                    updateParseJarFile(parseNameList, tempParseFolderPath,
                            parseFolderPath, parseFileName, parseName,
                            parseVersion);

                    sqlLineCount++;
                    if (sqlLineCount > maxSqlLine) {
                        // SELECT UNION ALL语句达到最大上限时添加到List<String>
                        // 去除结尾的UNION ALL
                        sbrJarListSelectSql.setLength(sbrJarListSelectSql
                                .length() - 10);
                        // 保存一组SELECT UNION ALL语句
                        jarSqlList.add(sbrJarListSelectSql.toString());
                        // 清空sbrSql，以便添加下一批sql语句
                        sbrJarListSelectSql.setLength(0);
                        sqlLineCount = 0;
                    }
                    // 拼接SELECT UNION ALL语句并将语句保存到StringBuilder
                    appendJarListSql(sbrJarListSelectSql, parseName,
                            parseVersion);
                    /*SDK-652 hewengao 20161025 start*/
//                    // 获取脚本sql文件，并进行脚本数据入库
//                    final File regexSqlFile = getRegexSqlFile(
//                            tempParseFolderPath, parseName);
//                    if (regexSqlFile != null) {
//                        try {
//                            insertRegex(regexSqlFile);
//                        } catch (Throwable e) {
//                            LogManager.e(Constant.TAG, e.getMessage(), e);
//                        }
//                    }
                    /*SDK-652 hewengao 20161025 end*/
                }
                /*SDK-652 hewengao 20161025 start*/
                insertRegexBySqlFile(tempParseFolderPath);
                /*SDK-652 hewengao 20161025 end*/
            } catch (Throwable e) {
                LogManager.e(Constant.TAG, "initAlgorithm: ", e);
            } finally {
                // parseNameList为null代表为第一次初始化，不需要删除重复数据
                if (parseNameList != null) {
                    try {
                        // 删除状态为初始化临时标记并重复的数据
                        ParseItemManager.deleteRepeatData();
                        // 将脚本状态设置为正常
                        ParseItemManager.updateStatue(ParseItemManager.INITTAG, ParseItemManager.NORMAL);
                    } catch (Throwable e) {
                        LogManager.e(Constant.TAG, e.getMessage(), e);
                    }
                }
            }

            insertJarSubInfo(jarSqlList, sbrJarListSelectSql);
            SysParamEntityManager.setParam(Constant.BEFORE_HAND_PARSE_SMS_TIME,
                    String.valueOf(System.currentTimeMillis()));
            // 只有更新了parseUtilMain.jar才进行删除老算法包的jar及dex文件
            if (needUpdateParseInfoMap.containsKey("parseUtilMain.jar")) {
                // 删除老算法包的jar及dex文件
                SysParamEntityManager.deleteOldFile();
                // 删除老算法包的数据记录
                JarSubInfoManager.deleteOldJar();
            }

            // 更新脚本jar版本号

            // 算法包升级，历史数据重新扫描
            /*ONEPLUSCII-98 songzhirong 20161226 start*/
            String config =  DuoquUtils.getSdkDoAction().getConfig(AbsSdkDoAction.CONFIG_NOTIFY_ALL_ALGORITHM, null);
            /*SDK-728 songzhirong 20170302 start */
            boolean flag = SysParamEntityManager.getBooleanParam(Constant.getContext(), Constant.CONFIG_NOTIFY_FIRST_TIME,true);
            if((StringUtils.isNull(config)||"true".equals(config)) && flag){
                JarSubCheckQueue.updateParseVersion();
            }
            /*SDK-728 songzhirong 20170302 end */

            /*ONEPLUSCII-98 songzhirong 20161226 end*/
            /*SDK-673 hewengao 20161114 start*/
            //chJarmod();
            /*SDK-673 hewengao 20161114 end*/
            SysParamEntityManager.setParam("sms_sdk_init", "1");
            /* SDK-567 huangzhiqiang 20160728 start */
            DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "initAlgorithm complete", null);
            /* SDK-567 huangzhiqiang 20160728 end */
            LogManager.i("initduoqu_parse", "初始化算法配置完成");
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "initAlgorithm: ", e);
        } finally {
            try {            	
                /*ONEPLUSCII-98 songzhirong 20161226 start*/
            	JarSubInfoManager.updateIsUse("ParseUtilCard",JarSubInfoManager.USED);    
                /*ONEPLUSCII-98 songzhirong 20161226 end*/            
                 /*SDK-691 hewengao 20161130 start*/
                FileUtils.renameFile(Constant.getTempPARSE_PATH()+"ScenesScanner.idx", Constant.getPARSE_PATH()+"ScenesScanner.idx");
                FileUtils.renameFile(Constant.getTempPARSE_PATH()+"ScenesScanner.obj", Constant.getPARSE_PATH()+"ScenesScanner.obj");
                /*SDK-691 hewengao 20161130 end*/
                /* SDK-493 hewngao 20160618 start */
            	FileUtils.renameFile(Constant.getTempPARSE_PATH()+"libxy-algorithm.so", Constant.getPARSE_PATH()+"libxy-algorithm.so");
            	FileUtils.renameFile(Constant.getTempPARSE_PATH()+"libxy-algorithm-64.so", Constant.getPARSE_PATH()+"libxy-algorithm-64.so");
            	/* SDK-493 hewngao 20160618 end */
                /*SDK-691 hewengao 20161130 start */
                renameInner();
                /*SDK-691 hewengao 20161130 end */
                // 删除临时文件夹parse_temp
            	FileUtils.deleteAllFile(Constant.getTempPARSE_PATH());
            } catch (Throwable e) {
                LogManager.e(Constant.TAG, "initAlgorithm: ", e);
            }
            /* SDK-567 huangzhiqiang 20160728 start */
            DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "initAlgorithm end", null);
            /* SDK-567 huangzhiqiang 20160728 end */
        }
    }
    /*SDK-691 hewengao 20161130 start*/
    private static void renameInner() {
        try {
            File dir = new File(Constant.getTempPARSE_PATH());
            File[] fs = dir.listFiles();
            File newDir = new File(Constant.getPARSE_PATH());
            if (!newDir.exists())
                newDir.mkdirs();
            for (File f : fs) {
                String name = f.getName();
                if (name.endsWith(".obj") || name.endsWith(".idx") || name.endsWith(".so") || name.endsWith(".model")) {
                    f.renameTo(new File(newDir, name));
                }
            }
        }catch (Throwable e){
            LogManager.e(Constant.TAG, "renameInner: ", e);
        }
    }
    /*SDK-691 hewengao 20161130 end*/
    /*SDK-652 hewengao 20161025 start*/
    private static void insertRegexBySqlFile(String sqlFileFolderPath) {
        try {
            List<File> sqlFileList = FileUtils.getFileList(sqlFileFolderPath, "PU", ".sql");
            if (sqlFileList == null || sqlFileList.size() == 0) {
                return;
            }
            for (File sqlFile : sqlFileList) {
                try {
                    if (verifyFileMD5(sqlFile)) {
                        insertRegex(sqlFile);
                    }
                } catch (Throwable e) {
                    LogManager.e(Constant.TAG, e.getMessage(), e);
                }
            }
        } catch (Throwable e) {
            LogManager.w(Constant.TAG, "insertRegexBySqlFile", e);
        }
    }
    /**
     * 验证文件的MD5值是否与MD5记录文件中的MD5一致，MD5记录文件必须与待验证文件于同一目录，MD5记录文件命名规则为(待验证文件名称.txt)
     *    例:
     *       待验证文件:PU01.jar
     *       MD5记录文件:PU01.txt
     * @param file
     * @return
     */
    private static boolean verifyFileMD5(File file) {
        if (file == null) {
            return false;
        }
        try {
            String pathDir = file.getPath().toString().replace(file.getName(), "");
            String fileName = file.getName().replace(".sql", "");
            File regexSqlFile = getRegexSqlFile(pathDir, fileName);
            if(regexSqlFile != null){
                return true;
            }
        } catch (Throwable e) {
            LogManager.w(Constant.TAG, "verifyFileMD5 error", e);
        }
        return false;
    }
    /*SDK-652 hewengao 20161025 end*/
    /**
     * 更新脚本jar版本号
     * 
     * @param jarSqlList
     * @param sbrJarListSelectSql
     */
    private static void insertJarSubInfo(List<String> jarSqlList, StringBuilder sbrJarListSelectSql) {
        // StringBuilder长度不为0代表有sql没有添加到List<String>
        if (sbrJarListSelectSql.length() > 0) {
            // 去除结尾的UNION ALL
            sbrJarListSelectSql
                    .setLength(sbrJarListSelectSql.length() - 10);
            jarSqlList.add(sbrJarListSelectSql.toString());
        }

        if (jarSqlList.size() > 0) {
            // 批量插入tb_jar_list，并删除重复数据
            JarSubInfoManager.insertJarSubInfo(jarSqlList);
        }
    }

    /**
     * 初始化公众号logo资源
     */
    public static void initPublicLogo() {
        // 本地版本号
        String localVersion = SysParamEntityManager.getStringParam(Constant.getContext(), Constant.PUBLIC_LOGO_VERSION);
        // Assets资源版本
        /* SDK-569 huangzhiqiang 20160728 start */
        String assetsVersion = StringUtils.trim(FileUtils.getAssetsTxtFileContent(Constant.PUBLIC_LOGO_VERSION_FILE));
        /* SDK-569 huangzhiqiang 20160728 end */

        /* SDK-567 huangzhiqiang 20160728 start */
        DuoquUtils.getSdkDoAction().logInfo(Constant.TAG,
                "initPublicLogo localVersion=" + localVersion + " assetsVersion=" + assetsVersion, null);
        /* SDK-567 huangzhiqiang 20160728 end */

        if (!StringUtils.isNull(localVersion) && !compareVersion(localVersion, assetsVersion)) {
            /* SDK-567 huangzhiqiang 20160728 start */
            DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "initPublicLogo complete", null);
            /* SDK-567 huangzhiqiang 20160728 end */
            return;
        }

        try {
            /* SDK-567 huangzhiqiang 20160728 start */
            DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "initPublicLogo start", null);
            /* SDK-567 huangzhiqiang 20160728 end */

            /* SDK-464 hewengao 20160530 start */
            XyUtil.unZip(FileUtils.getAssetManager().open("duoqu_publiclogo.zip"), "duoqu_publiclogo.zip",
                    Constant.getPath("duoqu_publiclogo"));
            /* SDK-464 hewengao 20160530 end */

            SysParamEntityManager.setParam(Constant.PUBLIC_LOGO_VERSION, assetsVersion);
            /* SDK-567 huangzhiqiang 20160728 start */
            DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "initPublicLogo complete", null);
            /* SDK-567 huangzhiqiang 20160728 end */
            LogManager.d("initInerData", "初始化公众号logo资源完成");
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "initPublicLogo: ", e);
        } finally {
            /* SDK-567 huangzhiqiang 20160728 start */
            DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "initPublicLogo end", null);
            /* SDK-567 huangzhiqiang 20160728 end */
        }
    }

    /**
     * 初始化图片资源
     */
    public static void initDrawble() {
        // 本地版本号
        String localVersion = SysParamEntityManager.getStringParam(
                Constant.getContext(), Constant.DRAWABLE_VERSION);
        // Assets资源版本
        /* SDK-569 huangzhiqiang 20160728 start */
        String assetsVersion = StringUtils.trim(FileUtils.getAssetsTxtFileContent(Constant.DRAWABLE_VERSION_FILE));
        /* SDK-569 huangzhiqiang 20160728 end */

        /* SDK-567 huangzhiqiang 20160728 start */
        DuoquUtils.getSdkDoAction().logInfo(Constant.TAG,
                "initDrawble localVersion=" + localVersion + " assetsVersion=" + assetsVersion, null);
        /* SDK-567 huangzhiqiang 20160728 end */

        if (!StringUtils.isNull(localVersion)
                && !compareVersion(localVersion, assetsVersion)) {
            /* SDK-567 huangzhiqiang 20160728 start */
            DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "initDrawble complete", null);
            /* SDK-567 huangzhiqiang 20160728 end */
            return;
        }

        try {
            /* SDK-567 huangzhiqiang 20160728 start */
            DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "initDrawble start", null);
            /* SDK-567 huangzhiqiang 20160728 end */

            /*SDK-464 hewengao 20160530 start*/
            XyUtil.unZip(
                    FileUtils.getAssetManager().open("duoqu_drawable.zip"), "drawable.zip",
                    Constant.getDRAWBLE_PATH());
            /*SDK-464 hewengao 20160530 end*/
            String path = Constant.getDRAWBLE_PATH() + File.separator
                    + "init.sql";

            /* SDK-396 huangzhiqiang 20160428 start */
            File sqlFile = new File(path);
            if (!sqlFile.exists()) {
                return;
            }
            /* SDK-396 huangzhiqiang 20160428 end */

            // 将现有数据的FUNC_CALL字段标记为10，用于删除重复数据
            if (SceneRuleManager.updateTag(10) == -1) {
                return;
            }
            try {
                /* SDK-396 huangzhiqiang 20160428 start */
                if (DBManager.excSql(sqlFile, true)) {
                    SysParamEntityManager.setParam(Constant.HAS_IMPORT_DRAWABLE_DATA, "true");
                    SysParamEntityManager.setParam(Constant.DRAWABLE_VERSION, assetsVersion);
                }
                /* SDK-396 huangzhiqiang 20160428 end */
            } catch (Throwable e) {
                LogManager.e(Constant.TAG, "initDrawble: ", e);
            } finally {
                // 删除重复数据
                SceneRuleManager.deleteRepeatData();
            }
            // 恢复FUNC_CALL字段为0
            SceneRuleManager.updateTag(0);
            /* SDK-567 huangzhiqiang 20160728 start */
            DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "initDrawble complete", null);
            /* SDK-567 huangzhiqiang 20160728 end */
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "initDrawble: ", e);
        } finally {
            /* SDK-567 huangzhiqiang 20160728 start */
            DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "initDrawble end", null);
            /* SDK-567 huangzhiqiang 20160728 end */
        }
    }

    /**
     * 初始化菜单数据
     */
    public static void initMenuData() {
        // 本地版本号
        String localVersion = SysParamEntityManager.getStringParam(
                Constant.getContext(), Constant.MENU_VERSION);
        // Assets资源版本
        /* SDK-569 huangzhiqiang 20160728 start */
        String assetsVersion = StringUtils.trim(FileUtils.getAssetsTxtFileContent(Constant.MENU_VERSION_FILE));
        /* SDK-569 huangzhiqiang 20160728 end */

        /* SDK-567 huangzhiqiang 20160728 start */
        DuoquUtils.getSdkDoAction().logInfo(Constant.TAG,
                "initMenuData localVersion=" + localVersion + " assetsVersion=" + assetsVersion, null);
        /* SDK-567 huangzhiqiang 20160728 end */

        if (!StringUtils.isNull(localVersion)
                && !compareVersion(localVersion, assetsVersion)) {
            /* SDK-567 huangzhiqiang 20160728 start */
            DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "initMenuData complete", null);
            /* SDK-567 huangzhiqiang 20160728 end */
            return;
        }

        try {
            /* SDK-567 huangzhiqiang 20160728 start */
            DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "initMenuData start", null);
            /* SDK-567 huangzhiqiang 20160728 end */
            initNeiQianSql();
            SysParamEntityManager.setParam(Constant.MENU_VERSION, assetsVersion);
            /* SDK-567 huangzhiqiang 20160728 start */
            DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "initMenuData complete", null);
            /* SDK-567 huangzhiqiang 20160728 end */
            LogManager.d("duoqu_test", "初始化菜单数据完成");
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "initMenuData: ", e);
        } finally {
            /* SDK-567 huangzhiqiang 20160728 start */
            DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, "initMenuData end", null);
            /* SDK-567 huangzhiqiang 20160728 end */
        }
    }

    /**
     * 版本号对比
     * 
     * @param localVersion
     *            本地版本
     * @param assetVersion
     *            Assets版本
     * @return true:Assets版本号比本地版本号大 false:本地版本号比Assets版本号大
     */
    public static boolean compareVersion(String localVersion,
            String assetVersion) {
        /* SDK-420 huangzhiqiang 20160430 start */

        // 本地版本号为空或超过15代表为异常版本号，识别为Assets版本号比本地版本号大
        if (StringUtils.isNull(localVersion) || localVersion.length() > 15) {
            return true;
        }

        long localVersionInt = -1;
        try {
            /* SDK-569 huangzhiqiang 20160728 start */
            localVersionInt = Long.valueOf(StringUtils.trim(localVersion));
            /* SDK-569 huangzhiqiang 20160728 end */
        } catch (NumberFormatException ex) {
            // 没有本地版本号或本地版本号不正确识别为Assets版本号比本地版本号大
            return true;
        }

        long assetVersionInt = -1;
        try {
            /* SDK-569 huangzhiqiang 20160728 start */
            assetVersionInt = Long.valueOf(StringUtils.trim(assetVersion));
            /* SDK-569 huangzhiqiang 20160728 start */
        } catch (NumberFormatException ex) {
            // asset下算法文件版本无或不正确且本地有版本识别为本地版本号比Assets版本号大
            return false;
        }
        /* SDK-420 huangzhiqiang 20160430 end */
        return assetVersionInt > localVersionInt;
    }

    public static String getAlgorithmVersion() {
        String version = "-1";
        ZipFile zf = null;
        try {
            FileUtils.deleteFile(Constant.getPath("duoqu_version")
                    + "duoqu_parse.zip");
            /*SDK-464 hewengao 20160530 start*/
            File resultFile = FileUtils.downFileFromInput(
                    Constant.getPath("duoqu_version"),
                    "duoqu_parse.zip",
                    FileUtils.getAssetManager()
                            .open("duoqu_parse.zip"));
            /*SDK-464 hewengao 20160530 end*/
            if (resultFile != null) {
                zf = new ZipFile(resultFile);
                for (Enumeration<?> entries = zf.entries(); entries
                        .hasMoreElements();) {
                    ZipEntry entry = ((ZipEntry) entries.nextElement());
                    if (StringUtils.isNull(entry.getName())) {
                        continue;
                    }
                    String fileName = new String(entry.getName().getBytes(
                            "8859_1"), "GB2312");
                    if (!StringUtils.isNull(fileName)
                            && fileName.equalsIgnoreCase("version.txt")) {
                        version = FileUtils.getStringFromInputStream(zf
                                .getInputStream(entry));
                        return version.trim();
                    }
                }
            }

        } catch (Throwable e) {
            // TODO: handle Throwable
        } finally {
            FileUtils.deleteFile(Constant.getPath("duoqu_version")
                    + "duoqu_parse.zip");
            FileUtils.close(zf);
        }
        return version;
    }

    /**
     * 获取所有需要更新的算法包名称对应版本号信息HashMap
     * 
     * @return
     */
    private static HashMap<String, String> getNeedUpdateParseInfoMap() {
        List<String> parseVersionInfoList = FileUtils
                .getAssetsTxtFileListInfo(Constant.ALGORITHM_VERSION_FILE);
        if (parseVersionInfoList == null || parseVersionInfoList.isEmpty()) {
            return null;
        }

        // 本地所有算法包名称对应版本号Map
        HashMap<String, String> localParseVersionInfoMap = JarSubInfoManager
                .queryAllJarInfoMap();
        HashMap<String, String> needUpdateParseInfoMap = new HashMap<String, String>();
        String[] parseVersionInfoArr = null;
        String jarFileName = null;
        String jarVersion = null;
        for (String parseVersionInfo : parseVersionInfoList) {
            parseVersionInfoArr = parseVersionInfo.split("=");
            if (parseVersionInfoArr.length != 2) {
                continue;
            }
            jarFileName = parseVersionInfoArr[0];
            jarVersion = parseVersionInfoArr[1];
            if (!StringUtils.isNull(jarFileName)
                    && !StringUtils.isNull(jarVersion)
                    && needUpateParse(localParseVersionInfoMap,
                            jarFileName.replace(".jar", ""), jarVersion)) {
                needUpdateParseInfoMap.put(jarFileName, jarVersion);
            }
        }

        return needUpdateParseInfoMap;
    }

    /**
     * 是否需要更新本地算法包
     * 
     * @param localParseVersionInfoMap
     *            包含本地所有算法名包名称对应版本号信息的HashMap
     * @param assetParseName
     *            assets下duoqu_parse_version.txt文件里单个算法包名
     * @param assetParseVersion
     *            assets下duoqu_parse_version.txt文件里单个算法包版本号
     * @return true:需要更新本地算发包 false:不需要更新本地算发包
     */
    private static boolean needUpateParse(
            HashMap<String, String> localParseVersionInfoMap,
            String assetParseName, String assetParseVersion) {
        if (localParseVersionInfoMap == null
                || localParseVersionInfoMap.isEmpty()
                || !localParseVersionInfoMap.containsKey(assetParseName)) {
            return true;
        }

        return compareVersion(localParseVersionInfoMap.get(assetParseName),
                assetParseVersion);
    }

    /**
     * 如果不存在duoqu_parse_verion.txt或duoqu_parse_version.
     * txt的内容不为新算法版本配置时走旧的初始化算法流程
     * 
     * @return true:走旧的初始化算法流程 false:走新的初始化算法流程
     */
    private static boolean runOldInitAlgorithm() {
        // Assets下版本文件内容
        String assetVersionFileContent = FileUtils
                .getAssetsTxtFileContent(Constant.ALGORITHM_VERSION_FILE);
        return ("-1".equals(assetVersionFileContent) || !assetVersionFileContent
                .contains("="));
    }

    /**
     * 更新算法包jar文件
     * 
     * @param parseNameList
     *            parse文件夹下去除后缀及版本号后的算法包名称
     * @param tempParseFolderPath
     *            temp_parse临时文件夹路径
     * @param parseFolderPath
     *            parse文件夹路径
     * @param parseFileName
     *            算法jar文件名称
     * @param parseName
     *            算法名称
     * @param parseVersion
     *            算法版本
     * @throws Throwable
     */
    private static void updateParseJarFile(List<String> parseNameList, String tempParseFolderPath,
            String parseFolderPath, String parseFileName, String parseName, String parseVersion) throws Exception {
        // parse文件夹下存在对应的算法包才进行删除旧算法包操作
        if (parseNameList != null && parseNameList.contains(parseName)) {
            // 删掉旧的jar和dex
            FileUtils.deleteFile(parseFolderPath, parseName + "_", ".jar", null);
            FileUtils.deleteDex(parseName + "_", ".dex", null);
            DexUtil.removeClassLoaderBySubname(parseName);
        }

        java.io.InputStream inputStream = FileUtils.getInputStreamFromFile(tempParseFolderPath + parseFileName);
        // temp_parse临时文件夹下不存在该jar直接返回
        if (inputStream == null) {
            return;
        }

        // 删除parse文件夹下名称相同的jar包
        FileUtils.deleteFile(parseFolderPath + parseFileName);
        // 从parse_temp文件夹下复制jar到parse文件夹
        FileUtils.downFileFromInput(parseFolderPath, parseFileName, inputStream);
        // 重命名新的jar
        FileUtils.renameFile(parseFolderPath, parseName + ".jar", parseName + "_" + parseVersion + ".jar");
        if ("parseUtilMain".equals(parseName)) {
            DexUtil.init();
        } else if ("OnlineUpdateCycleConfig".equals(parseName)) {
            DexUtil.initOnlineUpdateCycleConfig();
        } else if ("ParseVerifyCodeValidTime".equals(parseName)) {
            DexUtil.initParseVerifyCodeValidTime();
        }
    }

    /**
     * 拼接批量插入tb_jar_list需要使用的SELECT UNION ALL语句并将语句保存到StringBuilder
     * 
     * @param sbrSelectSql
     *            用于保存一组SELECT UNION ALL语句
     * @param parseName
     *            算法名称
     * @param parseVersion
     *            算法版本
     */
    private static void appendJarListSql(StringBuilder sbrSelectSql,
            String parseName, String parseVersion) {
        if (sbrSelectSql == null) {
            return;
        }
        sbrSelectSql.append("SELECT '");
        sbrSelectSql.append(parseName);
        sbrSelectSql.append("'name,'");
        sbrSelectSql.append(parseVersion.trim());
        sbrSelectSql.append("'version,");
        sbrSelectSql.append(JarSubInfoManager.getDefaultUsed(parseName));
        sbrSelectSql.append(" is_use UNION ALL ");
    }

    /**
     * 获取脚本sql文件
     * 
     * @param tempParseFolderPath
     *            temp_parse临时文件夹路径
     * @param parseName
     *            算法名称
     * @return null:脚本sql文件不存在或MD5验证失败
     */
    private static File getRegexSqlFile(String tempParseFolderPath,
            String parseName) {
        String regexSqlFilePath = tempParseFolderPath + parseName + ".sql";
        File regexSqlFile = new File(regexSqlFilePath);
        if (!regexSqlFile.exists() || !regexSqlFile.isFile()) {
            return null;
        }
        String fileMd5 = StringUtils.getFileMD5(regexSqlFilePath);
        if (StringUtils.isNull(fileMd5)) {
            return null;
        }
        String verifyMd5 = SigntureUtil.getVerifyCode(tempParseFolderPath,
                parseName + ".txt");
        if (StringUtils.isNull(verifyMd5)) {
            return null;
        }

        if (!fileMd5.equals(verifyMd5)) {
            return null;
        }

        return regexSqlFile;
    }

    /**
     * tb_regex数据入库
     */
    private static void insertRegex(File regexSqlFile) {
        if (regexSqlFile == null) {
            return;
        }
        BufferedReader bufferedReader = null;
        String dataLine = null;
        SQLiteDatabase db = null;
        android.database.sqlite.SQLiteStatement sqliteStatement = null;
        try {
            bufferedReader = new BufferedReader(new FileReader(regexSqlFile));
            db = BizportDBManager.getSQLiteDatabase();
            sqliteStatement = db
                    .compileStatement("INSERT INTO tb_regex(scene_id,match_id,regex_text,version_code,regex_type)VALUES(?,?,?,?,?)");
            db.beginTransaction();

            while ((dataLine = bufferedReader.readLine()) != null) {
                String sceneId = null;
                String matchId = null;
                String regexType = null;
                String versionCode = null;
                String regexText = null;

                try {
                    String remain = dataLine;
                    sceneId = remain.substring(0, remain.indexOf(",")).trim();
                    remain = remain.substring(remain.indexOf(",") + 1,
                            remain.length());
                    matchId = remain.substring(0, remain.indexOf(",")).trim();
                    remain = remain.substring(remain.indexOf(",") + 1,
                            remain.length());
                    regexType = remain.substring(0, remain.indexOf(",")).trim();
                    remain = remain.substring(remain.indexOf(",") + 1,
                            remain.length());
                    versionCode = remain.substring(0, remain.indexOf(","))
                            .trim();
                    regexText = remain.substring(remain.indexOf(",") + 1,
                            remain.length()).trim();
                } catch (Throwable e) {
//                    ex.printStackTrace();
                    LogManager.e(Constant.TAG, "insertRegex: ", e);

                    continue;
                }

                sqliteStatement.bindString(1, sceneId);
                sqliteStatement.bindString(2, matchId);
                sqliteStatement.bindString(3, regexText);
                sqliteStatement.bindString(4, versionCode);
                sqliteStatement.bindString(5, regexType);
                sqliteStatement.executeInsert();
            }
        } catch (Throwable e) {
//            ex.printStackTrace();
            LogManager.e(Constant.TAG, "insertRegex: ", e);

        } finally {
            if (db != null) {
                try {
                    if (db.inTransaction()) {
                        // 即使出现异常也将之前成功插入的数据入库
                        db.setTransactionSuccessful();
                        db.endTransaction();
                    }
                } catch (Throwable e) {
//                    e.printStackTrace();
                    LogManager.e(Constant.TAG, "insertRegex: ", e);

                }
                if (sqliteStatement != null) {
                    sqliteStatement.close();
                }
                BizportDBManager.close(db);
            }
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
//                ex.printStackTrace();
                LogManager.e(Constant.TAG, "insertRegex: ", e);

            }
        }
    }

    /**
     * 获取parse文件夹下去除后缀及版本号后的算法包名称
     * 
     * @param parseFolderPath
     *            parse文件夹路径
     * @return
     */
    public static List<String> getParseNameList(String parseFolderPath) {
        if (parseFolderPath == null) {
            return null;
        }

        File parseDirectory = new File(parseFolderPath);
        if (!parseDirectory.exists() || !parseDirectory.isDirectory()) {
            return null;
        }

        String[] jarFileNames = parseDirectory.list();
        if (jarFileNames == null || jarFileNames.length == 0) {
            return null;
        }

        List<String> parseNameList = new ArrayList<String>();
        int lastIndex = 0;
        for (String jarFileName : jarFileNames) {
            lastIndex = jarFileName.lastIndexOf("_");
            if (lastIndex == -1) {
                continue;
            }
            jarFileName = jarFileName.substring(0, lastIndex);
            parseNameList.add(jarFileName);
        }
        return parseNameList;
    }
    
    public static void chJarmod(){
        /*SDK-616 hewengao 20160912 start*/
        SmartSmsThreadPoolManager.iccidPool.execute(new Runnable() {
        /*SDK-616 hewengao 20160912 end*/
            public void run() {
                try {
                    String dir = Constant.getPARSE_PATH();
                   	/* SDK-476 songzhirong 20160607 start*/
                    if(StringUtils.isNull(dir)){
                    	return;
                    }
                   	/* SDK-476 songzhirong 20160607 end*/
                    File file = new File(dir);
                    File[] files = file.listFiles();
                    if(files!=null&&files.length>0){
                        for(int i=0;i<files.length;i++){
                            XyUtil.chmodSyn("640", files[i].getAbsolutePath());
                        }
                    }
                } catch (Throwable e) {
                    LogManager.e(Constant.TAG, "chJarmod =", e);
                }
                
            }
        });
    }

    /**
     * 更新算法包版本号
     */
    private static void updateSmartAlgorithmPver() {
        String pver = FileUtils.getAssetsPver(Constant.ALGORITHM_VERSION_FILE);
        if (StringUtils.isNull(pver)) {
            return;
        }

        String dbPver = SdkParamUtil.getParamValue(Constant.getContext(), Constant.SMART_ALGORITHM_PVER);
        if (StringUtils.isNull(dbPver) || pver.compareTo(dbPver) > 0) {
            SdkParamUtil.setParamValue(Constant.getContext(), Constant.SMART_ALGORITHM_PVER, pver);
        }
    }
    
    
    /*SMARTISAN-129 songzhirong 20160819 start*/ 
    public static void reInitAlgorithm(final Context context,final SdkCallBack xyCallBack){
        /* SDK-665 likuangkuang 20161109 start avoid redundant entrance */
        synchronized (reInitLock) {
            if (isReIniting)
                return;
            isReIniting = true;
        }
        /* SDK-665 likuangkuang 20161109 end */
        
        Constant.initContext(context);         
        Thread th = new Thread(new Runnable() {

            @Override
            public void run() {
                try {                        
                    JarSubInfoManager.deleteAll();
                    BizportDBManager.deleteOldData();                      
                    String tempParseFolderPath = Constant.getTempPARSE_PATH();
                    String parseFolderPath = Constant.getPARSE_PATH();
                    FileUtils.deleteAllFile(tempParseFolderPath);
                    FileUtils.deleteAllFile(parseFolderPath);
                    File file = Constant.getContext().getDir("outdex", Context.MODE_PRIVATE);
                    FileUtils.deleteAllFile(file);
                    InitUtil.initAlgorithm();
                    XyUtil.doXycallBack(xyCallBack, "0");
                } catch (Throwable e) {
                    LogManager.w(Constant.TAG, "clearOldData: ", e);
                    XyUtil.doXycallBack(xyCallBack, "-1");
                } finally {
                    /* SDK-665 likuangkuang 20161109 start */
                    isReIniting = false;
                    /* SDK-665 likuangkuang 20161109 end */
                }              
            }
        });
        
        th.setName("xythread-reInitAlgorithm");
        th.start();
    }
    /*SMARTISAN-129 songzhirong 20160819 end*/ 
}
